<template>
	<view>
		<view>
			<camera :device-position="device" :flash="flash" @error="error"
				:style="{ width: '100%',position: 'relative', height: getHeight + 'px' }">
				<cover-view class="topBox">
					<!-- 日期 -->
					<cover-view class="topItem">时间：{{nowTime}} {{nowTime2}}</cover-view>
					<!-- 地址 -->
					<cover-view class="topItem">地址：{{address}}</cover-view>
				</cover-view>

				<!-- 旋转摄像头 -->
				<cover-image @click="xzBtn" class="xzImg" src="/static/icon/xz.png"></cover-image>
				<!-- 打开/关闭 闪关灯 -->
				<!-- <cover-image @click="sgdBtn" class="sgdImg" :src="sgdUrl"></cover-image> -->
				<!-- 拍照 -->
				<cover-view class="cameraBtn" @click="takePhoto">
					<cover-view class="cameraBtn2"></cover-view>
				</cover-view>
				<!-- 底部预览生成图片 -->
				<!-- <cover-view class="bottomBg" v-if="imgList.length > 0">
					<cover-view>
						<cover-view @click="ViewImage(index)" class="imgBox" v-for="(item,index) in imgList" :key="index">
							<cover-image class="imgItem" :src="item.src" mode="aspectFill"></cover-image>
							<cover-view class="cu-tag" @tap.stop="DelImg" :data-index="index">
								<cover-image class="iconClose" src="https://cdn.zhoukaiwen.com/icon_close.png"
									mode="aspectFill"></cover-image>
							</cover-view>
						</cover-view>
					</cover-view>
				</cover-view> -->
			</camera>
			<view style="position: absolute;top: -999999px;">
				<view>
					<canvas :style="{ width: w, height: h }" canvas-id="firstCanvas"></canvas>
				</view>
			</view>
		</view>
		<view>
		</view>
	</view>
</template>
<script>
	// #ifdef APP-PLUS
	const watermark = uni.requireNativePlugin('WH-WatermarkPhoto');
	// #endif
	let countDownTime = undefined;
	// 水印模板的尺寸
	let tempSize = {};
	import dataBase from '@/common/dataBase.js';
	
	// var qqSDK = require('@/common/qqmap-wx-jssdk.min.js')
	// var qqMap;
	export default {
		components: {
		},
		name: "camera",
		data() {
			return {
				amapPlugin:null,
				cameraComIsShow: false,
				refreshKey: 0,
				location: {
					address: '四川省成都市青羊区 第十一中学11111',
					city: '成都市',
					province: '四川省',
					longitude: 121.4343,
					latitude: 31.3243
				},
				// 是否点击按住了水印模板视图
				isPressWaterMarkView: false,
				templateListDialogShow: false,
				// ---------------------
				getHeight: '200', // camera 组件高度
				device: 'back', //前置或后置摄像头，值为front, back
				flash: 'off', // 闪光灯，值为auto, on, off
				nowTime: '', //日期
				nowTime2: '', //时间
				address: '获取位置失败', //当前地址信息
				sgdUrl: 'https://cdn.zhoukaiwen.com/sgd.png', // 闪光灯图片地址
				imgList: [ // 底部预览图片的列表
					// {
					// 	src: "https://cdn.zhoukaiwen.com/angular.jpg"
					// }
				],
				w: '', // canvas 元素宽度
				h: '', // canvas 元素高度
				user: null,
				amapPlugin:null,
			}
		},
		onLoad() {
			dataBase.queryLocation().then(res=>{
				console.log("获取到位置信息：",res);
				this.address = res.province+res.city+res.poiName
			});
			this.user = uni.getStorageSync("user")
			uni.getSystemInfo({
				success: (res) => {
					this.getHeight = res.windowHeight;
				}
			});
			// 获取当前日期时间
			this.getTime();
		},
		onReady() {},
		methods: {
			getLocForAMpxWX() {
				this.amapPlugin.getRegeo({
					success: data => {
						// let res = data[0]
						// this.locationInfo = {
						// 	longitude: res.longitude,
						// 	latitude: res.latitude
						// };
						
						// this.myLoc.longitude = res.longitude;
						// this.myLoc.latitude = res.latitude;
						// let addName = res.regeocodeData.formatted_address;
						// let splitString = '##';
						// let location = res.longitude + ',' + res.latitude;
						// this.address = addName + splitString + location;
						console.log(thisdata);
						uni.hideLoading();
					},
					fail: err => {
						// this.$u.toast('定位失败！');
						console.log('定位失败:', err);
						uni.hideLoading();
					}
				})
			},
			getLocForQQ() {
				var _this = this //重定义this指向 *
				wx.getLocation({
					success: function(res) {
						console.log(11111,res);
						var latitude = res.latitude
						var longitude = res.longitude
						qqMap.reverseGeocoder({
							success: function(data) {
								let result = data.result
								_this.myLoc.longitude = result.location.lng;
								_this.myLoc.latitude = result.location.lat;
								// console.log(res.result.location.lat, '小') //这里可以查看返回的数据
								// console.log(res.result.location.lng, '大') //这里可以查看返回的数据
							}
						})
					}
				})
			},
			
			saveImage(url) {
				wx.downloadFile({
					url: url,
					success: (res) => {
						console.log(res)
						// if (res.statusCode === 200) {
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: () => {
								uni.showToast({
									title: '保存成功',
									icon: 'success'
								});
							},
							fail: () => {
								uni.showToast({
									title: '保存失败',
									icon: 'none'
								});
							}
						});
					},
					fail: () => {
						uni.showToast({
							title: '下载失败',
							icon: 'none'
						});
					}
				});
			},
			showCamera() {
				console.log(1111)
				this.cameraComIsShow = true
			},
			// 旋转摄像头
			xzBtn() {
				if (this.device == 'front') {
					this.device = 'back'
				} else {
					this.device = 'front'
				}
			},
			// 打开/关闭 闪光灯
			sgdBtn() {
				if (this.flash == 'off') {
					this.flash = 'on'
					this.sgdUrl = 'https://cdn.zhoukaiwen.com/sgd_on.png'
				} else {
					this.flash = 'off'
					this.sgdUrl = 'https://cdn.zhoukaiwen.com/sgd.png'
				}
			},
			// 删除水印照片
			DelImg(e) {
				uni.showModal({
					content: '确定要删除这张照片吗？',
					cancelText: '取消',
					confirmText: '确认',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			// 查看照片
			ViewImage(index) {
				const imgList = [this.imgList[index].src];
				uni.previewImage({
					urls: imgList
				});
			},
			// 点击拍照
			takePhoto() {
				var that = this;
				if (this.imgList.length < 3) {
					// 创建并返回 camera 组件的上下文 cameraContext 对象
					const ctx = uni.createCameraContext();
					// 拍照
					ctx.takePhoto({
						quality: 'high', // 图片质量高
						success: (res) => {
							var tempImagePath = res.tempImagePath; // 临时图片路径
							// 获取图片信息
							uni.getImageInfo({
								src: res.tempImagePath,
								success: ress => {
									that.w = ress.width / 3 + 'px'; // 设置 canvas 元素宽度
									that.h = ress.height / 3.01 + 'px'; // 设置 canvas 元素高度
									let ctx = uni.createCanvasContext('firstCanvas'); /** 创建画布 */
									//将图片绘制到cancas内
									ctx.drawImage(res.tempImagePath, 0, 0, ress.width / 3, ress
										.height / 3);

									ctx.setFontSize(10); // 设置字体大小为 10px
									ctx.setFillStyle('#FFFFFF'); // 设置颜色为白色

									let textToWidth = (ress.width / 3) * 0.03; // 绘制文本的左上角x坐标位置
									let textToHeight1 = (ress.height / 3) * 0.94; // 绘制文本的左上角y坐标位置
									let textToHeight2 = (ress.height / 3) * 0.98;
									// 绘制日期和时间
									ctx.fillText(that.nowTime + ' ' + that.nowTime2, textToWidth,
										textToHeight1);
									// 绘制地址
									ctx.fillText(that.address, textToWidth, textToHeight2);

									// 绘制完成后，在下一个事件循环将 canvas 内容导出为临时图片地址
									ctx.draw(false, () => {
										setTimeout(() => {
											uni.canvasToTempFilePath({
												canvasId: 'firstCanvas',
												success: res1 => {
													tempImagePath =
														res1
														.tempFilePath
													console.log(
														tempImagePath
														)
													// this.imgList.push({
													// 	src: tempImagePath
													// })
													uni.saveImageToPhotosAlbum({
														filePath: tempImagePath,
														success: () => {
															uni.showToast({
																title: '已保存至相册！',
																icon: 'success'
															});
														},
														fail: () => {
															uni.showToast({
																title: '保存失败',
																icon: 'none'
															});
														}
													});
												}
											});
										}, 1000);
									});
								}
							});
						}
					});
				} else {
					uni.showToast({
						title: '最大上传3张照片',
						duration: 2000,
						icon: 'none'
					});
				}
			},
			// 用户不允许使用摄像头时触发
			error(e) {
				console.log(e.detail);
			},
			// 获取日期时间
			getTime: function() {
				var date = new Date(),
					year = date.getFullYear(),
					month = date.getMonth() + 1,
					day = date.getDate(),
					hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
					minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
					second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
				month >= 1 && month <= 9 ? (month = "0" + month) : "";
				day >= 0 && day <= 9 ? (day = "0" + day) : "";
				var timer = year + '年' + month + '月' + day + '日';
				var timer2 = hour + ':' + minute + ':' + second;
				this.nowTime = timer;
				this.nowTime2 = timer2;
			},
			showWaterMarkListDialog(show) {
				if (show === 1) {
					dataBase.autoRunDelay = 200;
					this.templateListDialogShow = true;
					this.$refs.settingDialogObj.open(this.location, this.templateListDialogShow);
				} else {
					this.templateListDialogShow = false;
					this.$refs.settingDialogObj.close(this.templateListDialogShow);
				}
			},
			closeDialog() {
				// 延迟进入，避免隐藏模板列表窗口后，无法快速显示水印模板
				setTimeout(() => {
					dataBase.autoRunDelay = 1000;
				}, 600);
				// 这字段很重要，用于控制显示/隐藏水印和操作栏
				this.templateListDialogShow = false;
			},
			openCamera() {
				const that = this
				let parameter = {
					// 颜色传 8位  因为需要透明度 js中6位满足不了
					// markTitle背景颜色
					titleBackgroundColor: "#703281ff",
					// mark内容背景颜色
					contentBackgroundColor: "rgba(245, 101, 255, 0.5)",
					// mark标题文字
					markTitle: "项目名称",
					// mark标题是否可以更改（默认false
					// false 只在水印配置页面查看不可修改
					// true 可编辑标题
					markTitleIsEdit: false,
					//是否可编辑水印内容
					settingIsEdit: true,
					// 防伪码 不需要可不传 既不显示防伪码
					lockTag: "12312312312312",
					// options 数组
					options: [{
							label: "施 工 区 域 ",
							content: "河南省漂河市舞阳县吴城镇室",
							show: true, // switch 按钮的值 开 true  关 false
							disable: false, //内容是否可编辑 false 可编辑 true不可编辑
							editTitle: false, //头部是否可编辑 false 不可编辑 true 可编辑
						},
						{
							label: "施 工 内 容 ",
							content: "河南省深河市舞阳县吴城镇室河南省汉河市",
							show: true,
							disable: false,
							editTitle: false,
						},
						{
							label: "品   牌   图 ",
							content: "企业独有",
							show: false,
							disable: false,
							editTitle: false,
							code: 66
						},
						{
							label: "施工负责人 ",
							content: "邱峰",
							show: true,
							disable: false,
							editTitle: false,
						},
						{
							label: "勘 查 单 位 ",
							content: "天津市市辖区宝区黄庄农",
							show: true,
							disable: false,
							editTitle: false,
						},
						{
							label: "天          气 ",
							content: "多云21°",
							show: true,
							disable: false,
							editTitle: false,
						},
						{
							label: "地          点 ",
							content: "宁夏回族自治区中卫市海原县贾塘乡1249号207室",
							show: true,
							disable: false,
							editTitle: false,
						},
						{
							label: "经   纬   度 ",
							content: "24.6221N，118.0334TE",
							show: true,
							disable: false,
							editTitle: false,
						},
						{
							label: "备          注 ",
							content: "预计6个小时左右完工",
							show: true,
							disable: false,
							editTitle: false,
						},
						//不传底部不显示蓝色底部
						{
							label: "建 设 单 位",
							content: "中国电建集团昆明勘测设计研究院有限公司",
							show: true,
							disable: false,
							editTitle: false,
							code: 99
						},
					],
				};

				watermark.useWatermarkPhotoWithOptions(parameter, (ret) => {
					//权限判断 如果内部禁止拍照，可以使用这个弹出提示
					if (ret.imgPath === 'noperm') {
						uni.showToast({
							title: "暂无权限"
						})
					} else {
						that.title = `file://${ret.imgPath}`
						console.log(ret)
					}
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.topBox {
		width: 750rpx;
		box-sizing: border-box;
		padding: 30rpx;
		color: #EEEEEE;
		font-size: 34rpx;

		.topItem {
			width: 100%;
			white-space: pre-wrap;
			margin-bottom: 15rpx;
		}
	}

	.cameraBtn {
		width: 120rpx;
		height: 120rpx;
		line-height: 120rpx;
		border: 6rpx #FFFFFF solid;
		border-radius: 50%;
		padding: 8rpx;
		position: absolute;
		left: calc(50% - 60rpx);
		bottom: 210rpx;
	}

	.cameraBtn2 {
		width: 100%;
		height: 100%;
		border-radius: 50%;
		background-color: #FFFFFF;
		text-align: center;
		color: #007AFF;
	}

	.xzImg {
		width: 52rpx;
		height: auto;
		position: absolute;
		right: 44rpx;
		bottom: 580rpx;
	}

	.sgdImg {
		width: 40rpx;
		height: auto;
		position: absolute;
		right: 50rpx;
		bottom: 450rpx;
	}

	.bottomBtn {
		width: 100%;
		height: 150rpx;
		padding-bottom: 15rpx;
		position: absolute;
		bottom: 0;
		left: 0;
		text-align: center;
		display: flex;
		justify-content: space-between;

		.btn {
			width: 30%;
			height: 150rpx;
			font-size: 34rpx;
			color: #FFFFFF;
			line-height: 150rpx;
		}
	}

	.bottomBg {
		width: 100%;
		height: 170rpx;
		box-sizing: border-box;
		padding: 20rpx 30rpx 40rpx;
		position: absolute;
		bottom: 0;
		left: 0;
		background-color: rgba(0, 0, 0, .8);
		display: flex;
		justify-content: space-between;
		align-items: center;

		.imgBox {
			width: 110rpx;
			height: 110rpx;
			float: left;
			margin-right: 40rpx;
			position: relative;

			.cu-tag {
				position: absolute;
				right: 0;
				top: 0;
				border-bottom-left-radius: 2px;
				padding: 3px 5px;
				height: auto;
				background-color: rgba(0, 0, 0, 0.5);
				font-size: 10px;
				vertical-align: middle;
				font-family: Helvetica Neue, Helvetica, sans-serif;
				white-space: nowrap;
				color: #ffffff;
			}
		}

		.imgItem {
			width: 110rpx;
			height: 110rpx;
		}
	}

	.iconClose {
		width: 20rpx;
		height: 20rpx;
	}
</style>